//
//  QZRefreshFooterView.m
//  QZRefreshData
//
//  Created by 弘德集团 on 2018/4/14.
//  Copyright © 2018年 弘德集团. All rights reserved.
//

#import "QZRefreshFooterView.h"
#import "UIView+Frame.h"
@implementation QZRefreshFooterView
{
    CGFloat _originalScrollViewContentHeight;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.textForNormalState = @"上拉可以加载更多";
        self.stateIndicatorViewNormalTransformAngle = M_PI;
        self.stateIndicatorViewWillRefreshStateTransformAngle = 0;
        [self setRefreshState:QZRefreshViewStateNormal];
        
    }
    return self;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    self.activityIndicatorView.hidden = YES;
    _originalScrollViewContentHeight = self.scrollView.contentSize.height;
    self.center = CGPointMake(self.scrollView.width *0.5, self.scrollView.contentSize.height + self.height *0.5);
    self.hidden = [self shouldHide];
}

- (void)didMoveToSuperview{
    [super didMoveToSuperview];
    self.scrollViewEdgeinsets = UIEdgeInsetsMake(0, 0, self.height, 0);
}

- (BOOL)shouldHide
{
    if (self.isEffectedByNavigationController) {
        return (self.scrollView.bounds.size.height - QZKNavigationBarHeight > self.y); //  + self.scrollView.contentInset.bottom
    }
    return (self.scrollView.bounds.size.height> self.y); // + self.scrollView.contentInset.bottom
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (![keyPath isEqualToString:QZRefreshViewObservingKeyPath] || self.refreshState == QZRefreshViewStateRefreshing) return;
    
    CGFloat y = [change[@"new"] CGPointValue].y;
    CGFloat criticalY = self.scrollView.contentSize.height - self.scrollView.height + self.height + self.scrollView.contentInset.bottom;
    
    // 只有在 y>0 以及 scrollview的高度不为0 时才判断
    if ((y <= 0) || (self.scrollView.bounds.size.height == 0)) return;
    
    // 触发SDRefreshViewStateRefreshing状态
    if (y < criticalY && (self.refreshState == QZRefreshViewStateWillRefresh)) {
        [self setRefreshState:QZRefreshViewStateRefreshing];
    }
    
    // 触发SDRefreshViewStateWillRefresh状态
    if (y > criticalY && (QZRefreshViewStateNormal == self.refreshState)) {
        if (self.hidden) return;
        [self setRefreshState:QZRefreshViewStateWillRefresh];
    }
    
    // 如果scrollView内容有增减，重新调整refreshFooter位置
    if (self.scrollView.contentSize.height != _originalScrollViewContentHeight) {
        [self layoutSubviews];
    }
}

@end
